#include "CcJsonTool.h"

#include <QJsonDocument>
#include <QJsonObject>

CcJsonTool::CcJsonTool(QObject* parent)
:QObject(parent)
{

}

CcJsonTool::~CcJsonTool()
{
    
}

QString CcJsonTool::toJsonFromVariantMap(QVariantMap dataMap)
{
	// dataMap: {"cmd":"1001","data":{"content":"05:00","type":1}}
    QByteArray command = QJsonDocument(QJsonObject::fromVariantMap(dataMap)).toJson(QJsonDocument::Compact);

    return QString::fromUtf8(command);
}

bool CcJsonTool::parseJsonFromString(const QString& jsonData)
{
	// jsonData: {"cmd":"1001","data":{"content":"05:00","type":1}}
	QJsonParseError error;
	auto jsonDoc = QJsonDocument::fromJson(jsonData.toUtf8(), &error);
	if (error.error != QJsonParseError::NoError)
	{
		return false;
	}

	auto mapContent = jsonDoc.object().toVariantMap();
	if (!mapContent.contains("cmd") || !mapContent.contains("data"))
	{
		return false;
	}
	auto mapData = mapContent["data"].toMap();
	if (!mapData.contains("content"))
	{
		return false;
	}

	auto cmd = mapContent["cmd"].toString().toUInt();
	if (cmd == 1001)
	{
		auto type = mapData["type"].toInt();
		auto content = mapData["content"];
	}
	return true;
}